package com.learn.maven.search;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

/**
 * @author wangxing
 * @version 2020/6/10 13:51 Administrator
 */
public class ElasticsearchUtil {
    private static volatile TransportClient client = null;
    public static final String IP = "192.168.1.150";
    public static final int PORT = 9300;

    static {
        client = getClient();
    }

    private static TransportClient getClient() {
        if (client == null) {
            synchronized (new Object()) {
                if (client == null) {
                    //        设置集群名称
                    @SuppressWarnings("resource")
                    Settings settings = Settings.builder().put("cluster.name", "elasticsearch-cluster").build();
                    //创建client
                    try {
                        client = new PreBuiltTransportClient(settings)
                                .addTransportAddresses(new TransportAddress(InetAddress.getByName(IP), PORT));
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println("es连接成功，获取连接对象： " + client.toString());
        return client;
    }

    public static final String ESINDEX = "hongkong_article";
    public static final String ESTYPE = "hongkong_article";

    /**
     * @param client     es连接客户端
     * @param queryField 查询字段
     * @param queryStr   查询字段值
     */
    public static void queryData(TransportClient client, String queryField, String queryStr) {
        QueryBuilder builder = QueryBuilders.matchQuery(queryField, queryStr);
        SearchResponse searchResponse = client.prepareSearch(ESINDEX)
                .setTypes(ESTYPE)
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(builder)
                .setSize(10)
                .get();
        SearchHit[] searchHits = searchResponse.getHits().getHits();
        for (SearchHit searchHit : searchHits) {
            System.out.println(searchHit.getSourceAsString());
            String author = (String) searchHit.getSourceAsMap().get("author");
            String title = (String) searchHit.getSourceAsMap().get("title");
            String briefly = (String) searchHit.getSourceAsMap().get("briefly");
            String full_article_url = (String) searchHit.getSourceAsMap().get("full_article_url");
            String img_url = (String) searchHit.getSourceAsMap().get("img_url");
        }
    }

    /**
     * description 根据查询key=value结果删除数据
     *
     * @param client TransportClient
     * @param key
     * @param value
     */
    public static void deleteData(TransportClient client, String key, String value) {
        BulkByScrollResponse response = DeleteByQueryAction.INSTANCE.newRequestBuilder(client)
                .filter(QueryBuilders.matchQuery(key, value))
                .source("machine_class_2") //index
                .get();
        long deleted = response.getDeleted();
        System.out.print("delete where " + key + " = " + value + " : ");
        System.out.println(deleted == 1);
    }

    public class UpdateES {
        /**
         * @param queryField  查找的字段
         * @param queryStr    查找字段的值
         * @param updateField 更新的字段
         * @param updateStr   更新字段的值
         * @throws IOException
         * @throws ExecutionException
         * @throws InterruptedException
         */
        public void updateES(TransportClient client, String queryField,
                             String queryStr, String updateField, String updateStr)
                throws IOException, ExecutionException, InterruptedException {
            //TransportClient client = new EsUtils().getClient();
            String nameOfIndex = "hongkong_pic_new";
            String nameOfType = "hongkong_pic_new";
            QueryBuilder match = QueryBuilders.matchQuery(queryField, queryStr);

            SearchResponse res = client.prepareSearch(nameOfIndex)
                    .setTypes(nameOfType)
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setQuery(match)
                    .setSize(1)
                    .get();

            String doc_id = res.getHits().getHits()[0].getId();//找到要更新的id
            System.out.println(doc_id);
            UpdateRequest request = new UpdateRequest();
            request.index(nameOfIndex) //索引名
                    .type(nameOfType) //类型
                    .id(doc_id)//id
                    .doc(
                            XContentFactory.jsonBuilder()
                                    .startObject()
                                    .field(updateField, updateStr)//要修改的字段 及字段值
                                    .endObject()
                    );
            UpdateResponse response = client.update(request).get();
            System.out.println(response.status());

        }
    }
}
